// 圣经问答游戏 - 游戏核心逻辑

class QuizGame {
    constructor() {
        this.questions = {};
        this.currentQuestions = [];
        this.currentQuestionIndex = 0;
        this.currentQuestion = null;
        this.gameActive = false;
        this.difficulty = 'beginner';
        this.questionsPerGame = 10;
        this.questionStartTime = 0;
        this.gameStartTime = 0;
        this.selectedAnswer = null;
        this.hasAnswered = false;
        
        // 音效系统将通过全局audioSystem使用
        
        this.loadQuestions();
    }

    // 加载问题数据（分批加载并按难度归类）
    async loadQuestions() {
        try {
            console.log('🔄 开始加载问题数据(分批)…');
            const files = [
                './data/questions-beginner.json',
                './data/questions-intermediate.json',
                './data/questions-expert.json'
            ];
            const all = [];
            for (const file of files) {
                try {
                    const res = await fetch(file);
                    if (!res.ok) {
                        console.warn('⚠️ 无法加载文件：', file, res.status);
                        continue;
                    }
                    const arr = await res.json();
                    if (Array.isArray(arr)) all.push(...arr);
                } catch (e) {
                    console.warn('⚠️ 读取文件出错：', file, e);
                }
            }
            const grouped = { beginner: [], intermediate: [], expert: [] };
            for (const q of all) {
                const key = q.difficulty || 'beginner';
                if (grouped[key]) {
                    grouped[key].push({
                        id: q.id,
                        question: q.question,
                        options: q.options,
                        correct: q.answerIndex,
                        explanation: q.note || '',
                        reference: Array.isArray(q.refs) ? q.refs.join('；') : (q.refs || '')
                    });
                }
            }
            this.questions = grouped;
            console.log('✅ 问题数据加载成功', Object.keys(this.questions));
            console.log('📊 各难度问题数量:', {
                beginner: this.questions.beginner?.length || 0,
                intermediate: this.questions.intermediate?.length || 0,
                expert: this.questions.expert?.length || 0
            });
        } catch (error) {
            console.error('❌ 加载问题数据失败:', error);
            this.questions = this.getBackupQuestions();
            console.log('🔄 使用备用问题数据');
        }
    }

    // 备用问题数据（防止加载失败）
    getBackupQuestions() {
        return {
            explorer: [
                {
                    id: 1,
                    question: "根据圣经记载，上帝用了几天创造世界？",
                    options: ["5天", "6天", "7天", "8天"],
                    correct: 1,
                    explanation: "根据创世记1章，上帝用六天创造了天地万物，第七天安息。",
                    reference: "创世记 1:31-2:2"
                },
                {
                    id: 2,
                    question: "亚当和夏娃住在哪个园子里？",
                    options: ["伊甸园", "橄榄园", "葡萄园", "玫瑰园"],
                    correct: 0,
                    explanation: "上帝在东方的伊甸立了一个园子，把所造的人安置在那里。",
                    reference: "创世记 2:8"
                }
            ],
            adventurer: [
                {
                    id: 16,
                    question: "保罗在去大马士革的路上遇见了谁？",
                    options: ["天使", "耶稣", "彼得", "巴拿巴"],
                    correct: 1,
                    explanation: "保罗在去大马士革的路上遇见了复活的主耶稣，从此悔改信主。",
                    reference: "使徒行传 9:3-5"
                }
            ],
            hero: [
                {
                    id: 31,
                    question: "希伯来书的作者最可能是谁？",
                    options: ["保罗", "路加", "巴拿巴", "阿波罗"],
                    correct: 0,
                    explanation: "虽然希伯来书没有明确署名，但传统上认为是保罗所写。",
                    reference: "希伯来书"
                }
            ],
            legend: [
                {
                    id: 41,
                    question: "圣经中哪卷书被称为'小圣经'？",
                    options: ["诗篇", "罗马书", "约翰福音", "以赛亚书"],
                    correct: 0,
                    explanation: "诗篇被称为'小圣经'，因为它包含了圣经中几乎所有重要的主题。",
                    reference: "诗篇"
                }
            ]
        };
    }

    // 开始新游戏
    async startGame(difficulty = 'beginner') {
        console.log('🎮 开始游戏，难度:', difficulty);
        
        // 确保问题数据已加载
        if (!this.questions || Object.keys(this.questions).length === 0) {
            console.log('⏳ 等待问题数据加载...');
            await this.loadQuestions();
        }
        
        const __map = { explorer: 'beginner', adventurer: 'intermediate', hero: 'expert', legend: 'expert' };
        this.difficulty = __map[difficulty] || difficulty;
        this.gameActive = true;
        this.currentQuestionIndex = 0;
        this.gameStartTime = Date.now();
        
        // 重置计分系统
        if (window.scoringSystem) {
            window.scoringSystem.reset();
            window.scoringSystem.setDifficulty(difficulty);
        }
        
        // 选择问题
        this.selectQuestions();
        
        // 检查是否成功选择了问题
        if (this.currentQuestions.length === 0) {
            console.error('❌ 没有可用的问题数据');
            alert('抱歉，问题数据加载失败，请刷新页面重试。');
            return;
        }
        
        // 显示第一题
        this.showQuestion();
        
        this.playSound('click');
    }

    // 选择游戏问题
    selectQuestions() {
        console.log('🔍 选择问题，难度:', this.difficulty);
        console.log('📚 可用问题数据:', this.questions);
        
        const __map2 = { explorer: 'beginner', adventurer: 'intermediate', hero: 'expert', legend: 'expert' };
        const __key = __map2[this.difficulty] || this.difficulty;
        const availableQuestions = this.questions[__key] || [];
        console.log('📝 当前难度可用问题数:', availableQuestions.length);
        
        if (availableQuestions.length === 0) {
            console.error('❌ 没有找到对应难度的问题，难度:', this.difficulty);
            console.error('📊 问题数据结构:', Object.keys(this.questions));
            return;
        }

        // 随机选择问题
        const shuffled = [...availableQuestions].sort(() => Math.random() - 0.5);
        this.currentQuestions = shuffled.slice(0, Math.min(this.questionsPerGame, shuffled.length));
        console.log('✅ 成功选择问题数:', this.currentQuestions.length);
    }

    // 显示当前问题
    showQuestion() {
        if (this.currentQuestionIndex >= this.currentQuestions.length) {
            this.endGame();
            return;
        }

        this.currentQuestion = this.currentQuestions[this.currentQuestionIndex];
        this.hasAnswered = false;
        this.selectedAnswer = null;
        this.questionStartTime = Date.now();
        
        // 开始计时
        if (window.scoringSystem) {
            window.scoringSystem.startQuestion();
        }
        
        // 更新UI
        this.updateQuestionUI();
        this.updateProgressUI();
    }

    // 更新问题UI
    updateQuestionUI() {
        const questionText = document.getElementById('questionText');
        const optionButtons = document.querySelectorAll('.kids-option');
        
        console.log('🎯 更新问题UI');
        console.log('📝 问题元素:', questionText);
        console.log('🔘 选项按钮数量:', optionButtons.length);
        console.log('📋 当前问题:', this.currentQuestion);
        
        if (!questionText || !this.currentQuestion) {
            console.error('❌ 缺少必要元素或问题数据');
            return;
        }

        // 显示问题
        questionText.textContent = this.currentQuestion.question;
        console.log('✅ 问题文本已更新:', this.currentQuestion.question);
        
        // 更新选项按钮
        optionButtons.forEach((button, index) => {
            if (index < this.currentQuestion.options.length) {
                const optionText = button.querySelector('.option-text');
                if (optionText) {
                    optionText.textContent = this.currentQuestion.options[index];
                }
                button.style.display = 'flex';
                button.disabled = false;
                button.className = 'option-btn kids-option';
                button.onclick = () => this.selectAnswer(index);
                console.log(`✅ 选项${index + 1}已更新:`, this.currentQuestion.options[index]);
            } else {
                button.style.display = 'none';
            }
        });

        // 隐藏下一题按钮和反馈
        const nextBtn = document.getElementById('nextBtn');
        const feedback = document.getElementById('answerFeedback');
        if (nextBtn) nextBtn.style.display = 'none';
        if (feedback) {
            feedback.classList.remove('show');
            feedback.innerHTML = '';
        }
        
        console.log('🎉 问题UI更新完成');
    }

    // 更新进度UI
    updateProgressUI() {
        const progressFill = document.getElementById('progressFill');
        const currentQuestionSpan = document.getElementById('currentQuestion');
        const totalQuestionsSpan = document.getElementById('totalQuestions');
        const currentScore = document.getElementById('currentScore');
        const currentStreak = document.getElementById('currentStreak');
        
        if (progressFill) {
            const progress = ((this.currentQuestionIndex + 1) / this.currentQuestions.length) * 100;
            progressFill.style.width = `${progress}%`;
        }
        
        if (currentQuestionSpan) {
            currentQuestionSpan.textContent = this.currentQuestionIndex + 1;
        }
        
        if (totalQuestionsSpan) {
            totalQuestionsSpan.textContent = this.currentQuestions.length;
        }
        
        if (currentScore && window.scoringSystem) {
            currentScore.textContent = window.scoringSystem.currentScore;
        }
        
        if (currentStreak && window.scoringSystem) {
            currentStreak.textContent = window.scoringSystem.currentStreak;
        }
        
        console.log('📊 进度UI已更新:', `${this.currentQuestionIndex + 1}/${this.currentQuestions.length}`);
    }

    // 选择答案
    selectAnswer(answerIndex) {
        if (this.hasAnswered || !this.gameActive) return;
        
        this.selectedAnswer = answerIndex;
        this.hasAnswered = true;
        
        // 计算答题时间
        const answerTime = (Date.now() - this.questionStartTime) / 1000;
        
        // 检查答案是否正确
        const isCorrect = answerIndex === this.currentQuestion.correct;
        
        // 更新计分
        const scoreResult = window.scoringSystem ? window.scoringSystem.submitAnswer(isCorrect, answerTime) : { points: 0, bonus: 0 };
        
        // 更新选项样式
        this.updateOptionsAfterAnswer(isCorrect);
        
        // 显示反馈
        this.showAnswerFeedback(isCorrect, scoreResult);
        
        // 播放音效
        this.playSound(isCorrect ? 'correct' : 'wrong');
        
        // 显示下一题按钮
        const nextBtn = document.getElementById('nextBtn');
        if (nextBtn) {
            nextBtn.style.display = 'block';
            nextBtn.onclick = () => this.nextQuestion();
        }
        
        // 更新分数显示
        this.updateProgressUI();
    }

    // 更新选项样式（答题后）
    updateOptionsAfterAnswer(isCorrect) {
        const optionBtns = document.querySelectorAll('.option-btn');
        
        optionBtns.forEach((btn, index) => {
            btn.disabled = true;
            
            if (index === this.currentQuestion.correct) {
                btn.classList.add('correct');
            } else if (index === this.selectedAnswer && !isCorrect) {
                // 将被点击且错误的按钮标记为 wrong，用于红色样式
                btn.classList.add('wrong');
            }
        });
    }

    // 显示答案反馈
    showAnswerFeedback(isCorrect, scoreResult) {
        const feedback = document.getElementById('answerFeedback');
        if (!feedback) return;

        const feedbackClass = isCorrect ? 'feedback-correct' : 'feedback-incorrect';
        const title = isCorrect ? '✅ 回答正确！' : '❌ 回答错误';
        
        let bonusText = '';
        if (isCorrect) {
            bonusText = `<div class="score-details">
                <div>基础分数: +${scoreResult.score}</div>
                ${scoreResult.timeBonus > 1 ? `<div>时间奖励: ×${scoreResult.timeBonus}</div>` : ''}
                ${scoreResult.streakBonus > 1 ? `<div>连击奖励: ×${scoreResult.streakBonus}</div>` : ''}
                ${scoreResult.streak > 1 ? `<div>当前连击: ${scoreResult.streak}</div>` : ''}
            </div>`;
        }

        feedback.innerHTML = `
            <div class="${feedbackClass}">
                <div class="feedback-title">${title}</div>
                ${bonusText}
                <div class="feedback-explanation">
                    <strong>解释：</strong>${this.currentQuestion.explanation}
                </div>
                <div class="feedback-reference">
                    <strong>参考：</strong>${this.currentQuestion.reference}
                </div>
            </div>
        `;
        
        feedback.classList.add('show');
    }

    // 下一题
    nextQuestion() {
        this.currentQuestionIndex++;
        this.showQuestion();
        this.playSound('click');
    }

    // 结束游戏
    endGame() {
        this.gameActive = false;
        
        // 获取最终统计
        const gameStats = window.scoringSystem ? window.scoringSystem.getGameStats() : {
            totalQuestions: this.currentQuestions.length,
            correctAnswers: 0,
            score: 0,
            streak: 0,
            accuracy: 0
        };
        
        // 记录游戏结果
        const updatedStats = gameStorage.recordGameResult(gameStats);
        
        // 检查成就
        const gameHistory = gameStorage.getGameHistory();
        const newAchievements = achievementSystem.checkAchievements(updatedStats, gameStats, gameHistory);
        
        // 成就达成时不再播放独立成就音效（已移除）
        if (newAchievements.length > 0) {
            setTimeout(() => this.playSound('achievement'), 500);
        }
        
        // 显示结果页面
        this.showResults(gameStats, newAchievements);
    }

    // 显示结果
    showResults(gameStats, newAchievements = []) {
        // 切换到结果页面
        this.switchToPage('resultPage');
        
        // 更新结果显示
        const finalScore = document.getElementById('finalScore');
        const accuracyRate = document.getElementById('accuracyRate');
        const maxStreak = document.getElementById('maxStreak');
        const totalTime = document.getElementById('totalTime');
        const newBadges = document.getElementById('newBadges');
        
        if (finalScore) finalScore.textContent = gameStats.finalScore;
        if (accuracyRate) accuracyRate.textContent = `${gameStats.accuracy}%`;
        if (maxStreak) maxStreak.textContent = gameStats.maxStreak;
        if (totalTime) totalTime.textContent = `${gameStats.timeTaken}秒`;
        
        // 显示新获得的徽章
        if (newBadges) {
            newBadges.innerHTML = '';
            if (newAchievements.length > 0) {
                const badgeTitle = document.createElement('h3');
                badgeTitle.textContent = '🎉 获得新徽章！';
                newBadges.appendChild(badgeTitle);
                
                newAchievements.forEach(achievement => {
                    const badge = document.createElement('div');
                    badge.className = 'badge-item';
                    badge.innerHTML = `${achievement.icon} ${achievement.name}`;
                    newBadges.appendChild(badge);
                });
            }
        }
    }

    // 退出游戏（纯粹的状态清理，不弹窗）
    quitGame() {
        this.gameActive = false;
        this.playSound('click');
        console.log('🚪 游戏已退出');
        return true; // 返回true表示成功退出
    }

    // 重新开始游戏
    restartGame() {
        console.log('🔄 重新开始游戏，难度:', this.difficulty);
        this.startGame(this.difficulty);
        // 页面切换由外部调用者处理
    }

    // 切换页面
    switchToPage(pageId) {
        // 隐藏所有页面
        document.querySelectorAll('.page').forEach(page => {
            page.classList.remove('active');
        });
        
        // 显示目标页面
        const targetPage = document.getElementById(pageId);
        if (targetPage) {
            targetPage.classList.add('active');
        }
        
        // 更新欢迎页面的统计数据
        if (pageId === 'welcomePage') {
            this.updateWelcomePageStats();
        }
    }

    // 更新欢迎页面统计
    updateWelcomePageStats() {
        const stats = gameStorage.getUserStats();
        const totalQuestions = document.getElementById('totalQuestions');
        const totalBadges = document.getElementById('totalBadges');
        
        if (totalQuestions) totalQuestions.textContent = stats.totalQuestions;
        if (totalBadges) totalBadges.textContent = stats.totalBadges;
    }

    // 显示成就页面
    showAchievements() {
        this.switchToPage('achievementsPage');
        this.updateAchievementsDisplay();
        this.playSound('click');
    }

    // 更新成就显示
    updateAchievementsDisplay() {
        const achievementsGrid = document.getElementById('achievementsGrid');
        if (!achievementsGrid) {
            console.error('❌ 找不到成就网格元素');
            return;
        }

        const achievements = window.achievementSystem ? window.achievementSystem.getAllAchievements() : [];
        achievementsGrid.innerHTML = '';

        if (achievements.length === 0) {
            achievementsGrid.innerHTML = '<p style="text-align: center; color: #666;">暂无成就数据</p>';
            return;
        }

        achievements.forEach(achievement => {
            const card = document.createElement('div');
            card.className = `achievement-card ${achievement.unlocked ? 'unlocked' : 'locked'}`;
            
            card.innerHTML = `
                <div class="achievement-icon">${achievement.icon}</div>
                <div class="achievement-name">${achievement.name}</div>
                <div class="achievement-description">${achievement.description}</div>
                ${achievement.unlocked ? `<div class="unlock-date">解锁于: ${new Date(achievement.unlockedDate).toLocaleDateString('zh-CN')}</div>` : '<div class="lock-hint">继续努力解锁吧！</div>'}
            `;
            
            achievementsGrid.appendChild(card);
        });
        
        console.log(`✅ 已显示 ${achievements.length} 个成就`);
    }

    // 播放音效
    playSound(soundType) {
        const settings = gameStorage.getSettings();
        if (!settings.soundEnabled || !window.mp3AudioSystem) return;

        // 设置音量
        mp3AudioSystem.setVolume(settings.volume / 100);
        mp3AudioSystem.setEnabled(settings.soundEnabled);
        
        // 播放音效
        mp3AudioSystem.playSound(soundType);
    }

    // 获取难度名称
    getDifficultyName(difficulty) {
        const names = {
            beginner: '入门级',
            intermediate: '进阶级',
            expert: '专家级'
        };
        return names[difficulty] || difficulty;
    }

    // 获取当前游戏状态
    getGameState() {
        return {
            active: this.gameActive,
            difficulty: this.difficulty,
            currentQuestion: this.currentQuestionIndex + 1,
            totalQuestions: this.currentQuestions.length,
            score: window.scoringSystem ? window.scoringSystem.currentScore : 0,
            streak: window.scoringSystem ? window.scoringSystem.currentStreak : 0,
            accuracy: window.scoringSystem ? window.scoringSystem.getAccuracy() : 0
        };
    }

    // 暂停游戏
    pauseGame() {
        if (!this.gameActive) return;
        
        // 这里可以添加暂停逻辑
        // 比如显示暂停对话框，停止计时等
    }

    // 恢复游戏
    resumeGame() {
        if (!this.gameActive) return;
        
        // 这里可以添加恢复逻辑
        // 比如隐藏暂停对话框，继续计时等
    }
}

// 创建全局游戏实例
window.quizGame = new QuizGame();